import asyncio

from fastapi import APIRouter, WebSocket,WebSocketDisconnect,Request
from datetime import datetime, timedelta
import socket
from app.core.shared import cpu_monitor,vm_monitor,network_monitor,disk_monitor,process_monitor

wsclient = APIRouter(prefix="/api/process", tags=["进程管理"])



# WebSocket连接管理器
class ConnectionManager:
    def __init__(self):
        self.active_connections = []

    async def connect(self, websocket: WebSocket):
        await websocket.accept()
        self.active_connections.append(websocket)

    def disconnect(self, websocket: WebSocket):
        self.active_connections.remove(websocket)

    async def broadcast(self, message: str):
        for connection in self.active_connections:
            await connection.send_text(message)


manager = ConnectionManager()


@wsclient.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket, interval: int = 5):
    await manager.connect(websocket)
    try:
        while True:
            process_list = await process_monitor.get_top_processes()
            serialized_processes = [p.dict() for p in process_list]
            data = {
                "processes": serialized_processes,
                "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            }
            await websocket.send_json(data)
            await asyncio.sleep(interval)  # 按指定间隔发送数据
    except Exception as e:
        print(f"WebSocket error: {e}")
    finally:
        manager.disconnect(websocket)  # 确保断开连接时清理
